using Microsoft.AspNetCore.Mvc;
using JTZY.Model.Order.Dto;
using JTZY.Model.Order;
using JTZY.Service.Order.IOrderService;
using JTZY.Admin.WebApi.Filters;
using JTZY.Model.Goods.Dto;
using JTZY.Model.Goods;
using JTZY.Repository;
using JTZY.Service.Order;
using System.ComponentModel;
using JTZY.Model;
using Azure;
using JTZY.Infrastructure.Enums;
using static JTZY.Common.GlobalEnumVars;
using Newtonsoft.Json;
using StackExchange.Redis;

//创建时间：2024-10-28
namespace JTZY.Admin.WebApi.Controllers.Order
{
    /// <summary>
    /// 订单表
    /// </summary>
    [Verify]
    [Route("order/Corecmsorder")]
    public class CorecmsorderController : BaseController
    {
        /// <summary>
        /// 订单表接口
        /// </summary>
        private readonly ICorecmsorderService _CorecmsorderService;
        private readonly ICorecmsbillaftersalesService _corecmsbillaftersalesService;
        private readonly IRedisOperationRepository _redisOperationRepository;

        public CorecmsorderController(ICorecmsorderService CorecmsorderService, IRedisOperationRepository redisOperationRepository)
        {
            _CorecmsorderService = CorecmsorderService;
            _redisOperationRepository = redisOperationRepository;
        }

        /// <summary>
        /// 查询订单表列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        [HttpGet("list")]
        [ActionPermissionFilter(Permission = "corecmsorder:list")]
        public IActionResult QueryCorecmsorder([FromQuery] CorecmsorderQueryDto parm)
        {
            parm.userId = HttpContext.GetUId();
            var response = _CorecmsorderService.GetList(parm);
            return SUCCESS(response);
        }


        /// <summary>
        /// 查询订单表详情
        /// </summary>
        /// <param name="OrderId"></param>
        /// <returns></returns>
        [HttpGet("{OrderId}")]
        [ActionPermissionFilter(Permission = "corecmsorder:query")]
        public IActionResult GetCorecmsorder(string OrderId)
        {
            var response = _CorecmsorderService.GetInfo(OrderId);

            var info = response.Adapt<CorecmsorderDto>();

            return SUCCESS(info);
        }

        /// <summary>
        /// 导出订单表
        /// </summary>
        /// <returns></returns>
        [Log(Title = "订单表", BusinessType = BusinessType.EXPORT, IsSaveResponseData = false)]
        [HttpGet("export")]
        [ActionPermissionFilter(Permission = "corecmsorder:export")]
        public IActionResult Export([FromQuery] CorecmsorderQueryDto parm)
        {
            parm.PageNum = 1;
            parm.PageSize = 100000;
            var list = _CorecmsorderService.ExportList(parm).Result;
            if (list == null || list.Count <= 0)
            {
                return ToResponse(ResultCode.FAIL, "没有要导出的数据");
            }
            var result = ExportExcelMini(list, "订单表", "订单表");
            return ExportExcel(result.Item2, result.Item1);
        }


        [HttpPost("comfir")]
        [ActionPermissionFilter(Permission = "corecmsorder:edit")]
        [Log(Title = "订单确认", BusinessType = BusinessType.UPDATE)]
        public IActionResult Comfir([FromBody] CorecmsorderDto parm)
        {
            var modal = parm.Adapt<Corecmsorder>().ToUpdate(HttpContext);
            modal.Status = 1;
            long userId = HttpContext.GetUId();
            var response = _CorecmsorderService.comfir(modal, userId);

            return SUCCESS(response);
        }

        //[HttpPost("status")]
        //[ActionPermissionFilter(Permission = "corecmsorder:edit")]
        //[Log(Title = "订单状态修改", BusinessType = BusinessType.UPDATE)]
        //public IActionResult Status([FromBody] CorecmsorderDto parm)
        //{
        //    var modal = parm.Adapt<Corecmsorder>().ToUpdate(HttpContext);
        //    var response = _CorecmsorderService.comfir(modal);

        //    return ToResponse(response);
        //}

        [HttpPost("pack")]
        [ActionPermissionFilter(Permission = "corecmsorder:edit")]
        [Log(Title = "订单商品打包", BusinessType = BusinessType.UPDATE)]
        public IActionResult Pack([FromBody] OrderPackDto parm)
        {
            var userId = HttpContext.GetUId();
            var lockKey = "LOCK_PackOrder:user_" + userId;
            var lockHolder = Guid.NewGuid().ToString("N"); //锁持有者
            var redisUserLock = _redisOperationRepository.LockTake(lockKey, lockHolder, TimeSpan.FromSeconds(10));
            if (redisUserLock)
            {
                //var modal = parm.Adapt<Corecmsorder>().ToUpdate(HttpContext);
                var response = _CorecmsorderService.Pack(parm);
                if (response.status)
                {
                    return SUCCESS(response.data);

                }
                else
                {
                    return ToResponse(ResultCode.FAIL, response.msg);
                }
            }
            else
            {
                //jm.msg = "当前请求太频繁_请稍后再试";
                return ToResponse(ResultCode.FAIL, "当前请求太频繁_请稍后再试");
            }
        }

        [HttpPost("ship")]
        [ActionPermissionFilter(Permission = "corecmsorder:edit")]
        [Log(Title = "订单发货", BusinessType = BusinessType.UPDATE)]
        public async Task<IActionResult> Ship([FromBody] CorecmsorderDto parm)
        {
            var userId = HttpContext.GetUId();
            var modal = parm.Adapt<Corecmsorder>().ToUpdate(HttpContext);
            var lockKey = "LOCK_ShipOrder:user_" + userId;
            var lockHolder = Guid.NewGuid().ToString("N"); //锁持有者
            var redisUserLock = _redisOperationRepository.LockTake(lockKey, lockHolder, TimeSpan.FromSeconds(10));
            if (redisUserLock)
            {
                var response = await _CorecmsorderService.Ship(modal, userId);

                if (response.status)
                {
                    return SUCCESS(response.data);

                }
                else
                {
                    return ToResponse(ResultCode.FAIL, response.msg);
                }
            }
            else
            {
                //jm.msg = "当前请求太频繁_请稍后再试";
                return ToResponse(ResultCode.FAIL, "当前请求太频繁_请稍后再试");
            }
        }


        [HttpPost("take")]
        [ActionPermissionFilter(Permission = "corecmsorder:edit")]
        [Log(Title = "订单状态修改", BusinessType = BusinessType.UPDATE)]
        public IActionResult Take([FromBody] CorecmsorderDto parm)
        {
            var userId = HttpContext.GetUId();
            var modal = parm.Adapt<Corecmsorder>().ToUpdate(HttpContext);
            var lockKey = "LOCK_TakeOrder:user_" + modal.OrderId;
            var lockHolder = Guid.NewGuid().ToString("N"); //锁持有者
            var redisUserLock = _redisOperationRepository.LockTake(lockKey, lockHolder, TimeSpan.FromSeconds(10));
            if (redisUserLock)
            {
                var response = _CorecmsorderService.Take(modal, userId);

                if (response.status)
                {
                    return SUCCESS(response.data);

                }
                else
                {
                    return ToResponse(ResultCode.FAIL, response.msg);
                }
            }
            else
            {
                //jm.msg = "当前请求太频繁_请稍后再试";
                return ToResponse(ResultCode.FAIL, "当前请求太频繁_请稍后再试");
            }
        }


        /// <summary>
        /// 取消订单
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost("cancelOrder")]
        [Description("取消订单")]
        public async Task<IActionResult> CancelOrder([FromBody] FMStringId entity)
        {
            var jm = new WebApiCallBack();

            if (entity.id.Length == 0)
            {
                jm.msg = "请提交要取消的订单号";
                return ToResponse(ResultCode.FAIL, "请提交要取消的订单号");

            }
            var order = _CorecmsorderService.GetInfo(entity.id);
            if (order == null)
            {
                jm.msg = "没有订单";
                return ToResponse(ResultCode.FAIL, "没有订单");
            }

            var result = order.PayStatus == (int)OrderPayStatus.Yes ? await _CorecmsorderService.CancelOrderAndRefund(order.OrderId)
                : await _CorecmsorderService.CancelOrder(new string[] { entity.id });
            if (!result.status)
            {
                return ToResponse(ResultCode.FAIL, result.msg);
            }
            else
            {
                return SUCCESS(result.data);

            }

        }

        [HttpPost("cancelorderandrefund")]
        [Description("取消订单并退款")]
        public async Task<IActionResult> CancelOrderAndRefund([FromBody] FMStringId entity)
        {

            if (entity.id.Length == 0)
            {
                return ToResponse(ResultCode.FAIL, "请提交要取消的订单号");
            }

            if (string.IsNullOrEmpty(entity.id))
            {

                return ToResponse(ResultCode.FAIL, "请提交要取消的订单号");
            }

            var result = await _CorecmsorderService.CancelOrderAndRefund(entity.id);

            if (!result.status)
            {
                return ToResponse(ResultCode.FAIL, result.msg);
            }
            else
            {
                return SUCCESS(result.data);

            }

        }

        [HttpGet("rePrintOrder")]
        [ActionPermissionFilter(Permission = "corecmsorderitem:query")]
        public async Task<IActionResult> RePrintOrder(string orderId)
        {
            long userId = HttpContext.GetUId();
            var response = _CorecmsorderService.GetInfo(orderId);
            response.Reprint = true;
            await _redisOperationRepository.ListLeftPushAsync(RedisMessageQueueKey.OrderPrint, JsonConvert.SerializeObject(response));
            var info = response.Adapt<List<CorecmsorderDto>>();
            return SUCCESS(info);
        }


        [HttpGet("orderdetilas")]
        [ActionPermissionFilter(Permission = "corecmsorder:query")]
        public async Task<IActionResult> OrderDetails(string OrderId)
        {
            var result = await _CorecmsorderService.GetOrderInfoByOrderId(OrderId);

            if (!result.status)
            {
                return ToResponse(ResultCode.FAIL, result.msg);
            }
            else
            {
                return SUCCESS(result.data);

            }
        }
    }
}